/*
 *  Copyright 2008-2010 www.jrails.org
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.rails.core.web;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.rails.core.GLOBAL;
import org.rails.core.util.Utils;

/**
 * 查询字符串生成类,根据HashMap键值来生成一致的查询字符串。
 * @author jack
 *
 */
@SuppressWarnings("serial")
public class QueryString extends HashMap<String,Object> {
	

	public QueryString(){
		super();
	}
	
	public QueryString(Map<String,Object> m){
		super(m);
	}
	
	@SuppressWarnings("unchecked")
	public Object put(String key,Object value){
		List<Object> values = null;
		if(this.containsKey(key)){
			if(get(key) instanceof List){
				values = (List<Object>)get(key);
				values.add(value);
			}else{
				values = new ArrayList<Object>();
				values.add(get(key));
				values.add(value);
			}			
			return super.put(key, values);
		}else{
			return super.put(key, value);
		}
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String toQueryString() throws IOException{
		final List<String> keys = Utils.getKeys(this);
		final StringBuffer qs = new StringBuffer();
		for(int i = 0;i < keys.size();i++){
			String k = keys.get(i);
			Object v = this.get(k);
			if(v instanceof List){
				List ls = (List)v; 
				for(int j = 0;j < ls.size();j++){
					qs.append(Utils.format("{0}={1}",k,URLEncoder.encode(Utils.def(ls.get(j),"").toString(),GLOBAL.REQUEST_CHARSET_NAME)));
					if(j < ls.size()-1)
						qs.append("&");
				}				
			}else{
				qs.append(Utils.format("{0}={1}",k,URLEncoder.encode(Utils.def(v,"").toString(),GLOBAL.REQUEST_CHARSET_NAME)));
			}
			if(i < keys.size()-1)
				qs.append("&");
		}
		return qs.toString();
	}
	
}
